<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1100px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
      :inline="true"
    >
      <el-form-item label="仓库" prop="warehouseId">
        <el-select
          v-model="formData.warehouseId"
          placeholder="请输入仓库"
          :clearable="true"
          :disabled="isEdit || isShow"
        >
          <el-option
            v-for="dict in materialWarehouse"
            :key="dict.id"
            :label="dict.warehouseName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select
          v-model="formData.supplierId"
          placeholder="请输入供应商"
          :clearable="true"
          :disabled="isShow"
        >
          <el-option
            v-for="dict in materialSupplier"
            :key="dict.id"
            :label="dict.supplierName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="要求到货日期" prop="arrivalTime" :disabled="isShow">
        <el-date-picker
          v-model="formData.arrivalTime"
          placeholder="请输入要求到货日期"
          :clearable="true"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="发货人姓名" prop="senderName" :disabled="isShow">
        <el-input v-model="formData.senderName" placeholder="请输入发货人姓名" :clearable="true" />
      </el-form-item>
      <el-form-item label="发货人手机号" prop="senderMobile" :disabled="isShow">
        <el-input
          v-model="formData.senderMobile"
          placeholder="请输入发货人手机号"
          :clearable="true"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark" :disabled="isShow">
        <el-input v-model="formData.remark" placeholder="请输入备注" :clearable="true" />
      </el-form-item>
    </el-form>
    <el-form-item :style="{ display: isShow ? 'none' : 'block' }">
      <el-button @click="clickAddMaterial">添加物资</el-button>
      <el-button @click="clickDeleteMaterial">删除物资</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :data="formData.details"
      save-key="MaterialPurchaseEdit"
      :row-style="rowStyle"
      @row-click="handleRowClick"
      height="400"
    >
      <template #number="{ row }">
        <InputNumber v-model="row.number" class="!w-100px" type="decimal" :disabled="isShow" />
      </template>
      <template #batchNo="{ row }">
        <el-input v-model="row.batchNo" class="!w-100px" :disabled="isShow" />
      </template>
      <template #productionDate="{ row }">
        <el-date-picker
          v-model="row.productionDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 130px !important"
          :disabled="isShow"
        />
      </template>
      <template #expireDate="{ row }">
        <el-date-picker
          v-model="row.expireDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 130px !important"
          :disabled="isShow"
        />
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <MaterialInfoSelect ref="materialInfoSelectRef" @select-value="handleSelectMaterialInfo" />
</template>
<script setup name="MaterialPurchaseEdit" lang="ts">
import * as MaterialPurchaseApi from '@/api/material/purchase'
import * as MaterialWarehouseApi from '@/api/material/warehouse'
import * as MaterialSupplierApi from '@/api/material/supplier'
import * as MaterialPurchaseModel from '@/model/material/order/MaterialPurchase'
import MaterialInfoSelect from '../materialInfo/MaterialInfoSelect.vue'
import * as MaterialPurchaseDetailModel from '@/model/material/order/MaterialPurchaseDetail'
import { MaterialPurchaseStatusEnum } from '@/utils/constants'
interface MaterialPurchaseDetailEdit extends MaterialPurchaseDetailModel.MaterialPurchaseDetail {
  'material.materialName': string
  'material.category.categoryName': string
  'material.price': string
  'material.materialSpecification': string
  operateType: string
}
interface MaterialPurchaseEdit extends MaterialPurchaseModel.MaterialPurchase {
  details: MaterialPurchaseDetailEdit[]
}
const message = useMessage()
const { t } = useI18n()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const isEdit = ref(false)
const isShow = ref(false)
const materialInfoSelectRef = ref()
const formData = ref<MaterialPurchaseEdit>({
  id: undefined,
  status: 0,
  purchaseNo: '',
  warehouseId: undefined,
  supplierId: undefined,
  arrivalTime: undefined,
  senderName: '',
  senderMobile: '',
  remark: '',
  details: []
})
const formRules = reactive({
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  supplierId: [{ required: true, message: '供应商不能为空', trigger: 'blur' }]
})
const tableCurrentRow = ref<MaterialPurchaseDetailEdit>()
let formType = ''
const materialWarehouse = ref()
const materialSupplier = ref()
const columns = [
  {
    label: '物资名称',
    prop: 'material.materialName'
  },
  {
    label: '物资类别名称',
    prop: 'material.category.categoryName'
  },
  {
    label: '销售单价',
    prop: 'material.price'
  },
  {
    label: '物资规格',
    prop: 'material.materialSpecification'
  },
  {
    label: '数量',
    prop: 'number',
    slot: 'number',
    minWidth: '100'
  },
  {
    label: '批次号',
    prop: 'batchNo',
    slot: 'batchNo',
    minWidth: '100'
  },
  {
    label: '生产日期',
    prop: 'productionDate',
    slot: 'productionDate',
    minWidth: '130'
  },
  {
    label: '有效期',
    prop: 'expireDate',
    slot: 'expireDate',
    minWidth: '130'
  }
]

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  materialWarehouse.value = await MaterialWarehouseApi.simpleList()
  materialSupplier.value = await MaterialSupplierApi.simpleList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    isEdit.value = true
    try {
      formData.value = await MaterialPurchaseApi.singleGet(id)
      if (formData.value.status != MaterialPurchaseStatusEnum.PENDING_REVIEW) {
        isShow.value = true
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MaterialPurchaseEdit
    if (formType === 'create') {
      await MaterialPurchaseApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await MaterialPurchaseApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = (row: MaterialPurchaseDetailEdit | undefined) => {
  tableCurrentRow.value = row
}

/** 重置表单 */
const resetForm = () => {
  isShow.value = false
  isEdit.value = false
  formData.value = {
    id: undefined,
    status: 0,
    purchaseNo: '',
    warehouseId: undefined,
    supplierId: undefined,
    arrivalTime: undefined,
    senderName: '',
    senderMobile: '',
    remark: '',
    details: []
  }
  formRef.value?.resetFields()
}

const clickAddMaterial = () => {
  materialInfoSelectRef.value.open()
}

const clickDeleteMaterial = () => {
  if (tableCurrentRow.value === undefined) {
    message.alertError('请选择要删除的物资')
    return
  }
  if (formType === 'create' || tableCurrentRow.value.id == undefined) {
    const index = formData.value.details.indexOf(tableCurrentRow.value)
    formData.value.details.splice(index, 1)
  } else {
    tableCurrentRow.value.operateType = 'delete'
  }
}

const handleSelectMaterialInfo = (selectMaterialInfoList) => {
  selectMaterialInfoList.forEach((element) => {
    const detail = {
      id: undefined,
      purchaseId: formType === 'create' ? undefined : formData.value.id,
      materialId: element.id,
      'material.materialName': element.materialName,
      'material.category.categoryName': element.category.categoryName,
      'material.price': element.price,
      'material.materialSpecification': element.materialSpecification,
      number: 1,
      inNumber: 0,
      batchNo: '',
      productionDate: '',
      expireDate: '',
      operateType: 'new'
    }
    formData.value.details.push(detail)
  })
}
</script>
